<?php
class UserRelation extends Zend_Db_Table_Abstract {
	
	const FRIEND = 2;
	const CONTACT = 1;
	
	protected $_name = 'user_relation';
	protected $_primary = 'id';
	
	protected $_referenceMap = array(
		'OriginalUser' => array(
			'columns' => 'original_user_id',
			'refTableClass' => 'User',
			'refColumns' => 'id'
		),
		'PotentialUser' => array(
			'columns' => 'potential_user_id',
			'refTableClass' => 'User',
			'refColumns' => 'id'
		),
		'RelationType' => array(
			'columns' => 'relation_type',
			'refTableClass' => 'RelationType',
			'refColumns' => 'id'
		)
	);
	
	/**
	 * Find user relation by given original user id, potential user id and relation type.
	 * 
	 * @param $original_user_id
	 * @param $potential_user_id
	 * @param $relation_type
	 */
	public static function findUnique($original_user_id, $potential_user_id, $relation_type) {
		$userRelation = new UserRelation();
		$select = $userRelation->select()
		->where('original_user_id=?', $original_user_id)
		->where('potential_user_id=?', $potential_user_id)
		->where('relation_type=?', $relation_type);
		return $userRelation->fetchRow($select);
	}
	
	/**
	 * Delete user relation, right now, only contact (relation type 1).
	 * 
	 * @param $original_user_id
	 * @param $potential_user_id
	 * @param $relation_type
	 */
	public static function deleteUserRelation($original_user_id, $potential_user_id, $relation_type) {
		$userRelation = UserRelation::findUnique($original_user_id, $potential_user_id, $relation_type);
		$userRelation->delete();
	}
	
	/**
	 * Add or update user relation.
	 * 
	 * @param $data
	 */
	public static function addOrUpdateUserRelation($data) {
		$userRelation = UserRelation::findUnique($data['original_user_id'], $data['potential_user_id'], $data['relation_type']);
		if (!isset($userRelation)) {
			$userRelation = new UserRelation();
			$userRelation->insert($data);
		} else {
			$userRelation->alias = $data['alias'];
			$userRelation->save();
		}
		return $userRelation;
	}
	
	/**
	 * Find all friends.
	 */
	public static function findAllFriends() {
		$friends = array();
		$user = new User();
		$userRelation = new UserRelation();
		$select = $userRelation->select()
		->where('relation_type=?', self::FRIEND);
		
		$index = 0;
		foreach($userRelation->fetchAll($select) as $u) {
			$friends[$index++] = new Custom_Friend($u->id, $user->findById($u->original_user_id), $user->findById($u->potential_user_id));
		}
		return $friends;
	}
}

?>